﻿using System.Collections.Generic;
using UnityEngine;
using HotUpdateMessage;
using System;

namespace UnityEngine
{
    [Serializable]
    public class ReferenceData
    {
        public string name;
        public Object Object;
        public bool deleteField = false;
    }
    public class ReferenceManage : MonoBehaviour
    {
        private string HorUpdateScriptnNamespace = Defines.HorUpdateScriptnNamespace;

        /// <summary>
        /// 需要同步的热更新脚本
        /// </summary>
        public string ButtJoinHorUpdateScript;


        /// <summary>
        /// 引用名称
        /// </summary>
        public List<ReferenceData> objectList = new List<ReferenceData>();

        /// <summary>
        /// 引用字典
        /// </summary>
        public Dictionary<string, GameObject> dicRefManage = new Dictionary<string, GameObject>();

        public Dictionary<string, Object> testDir = new Dictionary<string, Object>();

        public bool switcher = true;

        private void Awake()
        {
            HorUpdateScriptnNamespace = Defines.HorUpdateScriptnNamespace;
            // 初始化发送引用

            AddReference();
            //Debug.Log("我是初始化");
            //foreach (var item in dicRefManage)
            //{
            //    Debug.Log("字典的key:" + item.Key);
            //}
            MessageCenter.Send("Reference", this, dicRefManage);

        }

        private void Start()
        {


        }

        private void OnValidate()
        {
            //if (objectList != null)
            //{
            //    AddReference();
            //    Debug.Log("运行时我是不会被调用的");
            //}
            //HorUpdateScriptnNamespace = Defines.HorUpdateScriptnNamespace;
        }

        private void AddReference()
        {

            dicRefManage.Clear();
            dicRefManage.Add(HorUpdateScriptnNamespace + "." + ButtJoinHorUpdateScript, this.gameObject);
            //Debug.Log(objectList.Count);
            for (int i = 0; i < objectList.Count; i++)
            {
                if (objectList[i].Object == null)
                    continue;
                if (objectList[i].name.Contains("("))
                {
                    int index = objectList[i].name.IndexOf("(");
                    string objName = objectList[i].name.Remove(index);
                }
                try
                {
                    if (objectList[i].Object is GameObject)
                    {
                        dicRefManage.Add(objectList[i].name, objectList[i].Object as GameObject);
                    }
                    else
                    {
                        // 待完善
                    }
                    //Debug.Log("字典的值:" + dicRefManage[objectList[i].name]);
                }
                catch (Exception)
                {
                    Debug.LogError("引用保存失败,您的引用中有相同的引用名称, 请修改引用");
                    return;
                }

            }
        }

    }
}

